package com.cmcc.passenger.ui.tripoption

import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.cmcc.passenger.R
import com.cmcc.passenger.config.AppConfig
import com.cmcc.passenger.config.IntentKeys
import com.cmcc.passenger.config.PassPath
import com.cmcc.passenger.data.entity.response.*
import com.cmcc.passenger.databinding.ActivityTripOptionsBinding
import com.cmcc.passenger.ui.base.BasicActivity
import com.cmcc.passenger.ui.fragment.AppProgressDialog
import com.cmcc.passenger.ui.tripoption.adapter.OnOptionItemCheckedListener
import com.cmcc.passenger.ui.tripoption.adapter.OnRemarkItemCheckedListener
import com.cmcc.passenger.ui.tripoption.adapter.OptionItemAdapter
import com.cmcc.passenger.ui.tripoption.adapter.RemarkItemAdapter
import com.cmcc.passenger.ui.utils.NumberUtils
import com.cmcc.shared.adapter.TripOptionItemDecoration
import com.cmcc.shared.utils.DisplayUtil
import com.cmcc.shared.utils.L
import com.cmcc.shared.utils.clickWithTrigger

@Route(path = PassPath.TRIP_OPTIONS)
class TripOptionsActivity : BasicActivity() {
    /**
     * binding view which init later.
     */
    private lateinit var binding: ActivityTripOptionsBinding
    /**
     * 隧道列表适配器
     */
    private var tunnelAdapter: OptionItemAdapter<Tunnel>? = null
    /**
     * 打赏小费列表适配器
     */
    private var gratuityAdapter: OptionItemAdapter<Gratuity>? = null
    /**
     * 车种列表适配器
     */
    private var carTypeAdapter: OptionItemAdapter<CarCategory>? = null
    /**
     * 站台列表适配器
     */
    private var stationAdapter: OptionItemAdapter<Station>? = null

    private var remarkAdapter: RemarkItemAdapter<Remark>? = null
    /**
     * 绑定的ViewModel.实际与model交互的逻辑会写到里面。
     */
    private lateinit var viewModel: TripOptionsViewModel
    /**
     * 订单请求模型，从上一个界面中传递过来，存有更多出行选项的一些信息。
     */
    private lateinit var orderRecord: OrderRecord
    /**
     * 加载框
     */
    private lateinit var progressDialog: AppProgressDialog


    override fun initialize(savedInstanceState: Bundle?) {
        L.d("TripOption initialize")
        binding = DataBindingUtil.setContentView(this, R.layout.activity_trip_options)
        viewModel = ViewModelProviders.of(this).get(TripOptionsViewModel::class.java)
        //注意一下 可能会空
        val origin = intent.getStringExtra(IntentKeys.DIRECTION_ORIGIN)
        val destination = intent.getStringExtra(IntentKeys.DIRECTION_DESINATION)
       // orderRecord = intent.getParcelableExtra(IntentKeys.ORDER_REQUEST) ?: OrderRecord()
        orderRecord = AppConfig.response!!
        binding.directions.directionStart.text = origin
        binding.directions.directionEnd.text = destination
        binding.toolbar.title.text = getString(R.string.passenger_more_options_about_trip)
        binding.toolbar.toolbar.setNavigationOnClickListener { finish() }

        binding.layoutCarRemarks.remarkContent.setText(orderRecord.remark)

        binding.buttonSave.clickWithTrigger {
            val intent = Intent()
            orderRecord.remark = binding.layoutCarRemarks.remarkContent.text.toString()
            //intent.putExtra(IntentKeys.ORDER_REQUEST, orderRecord)
            orderRecord = AppConfig.response!!
            setResult(Activity.RESULT_OK, intent)
            finish()
        }

        binding.navigationButton.clickWithTrigger {
            finish()
        }

//        binding.layoutCarTip.amountOfTip.addTextChangedListener(object : TextWatcher {
//            override fun afterTextChanged(s: Editable?) {
//                if (orderRecord.bountyFee != s.toString()) {
////                    orderRecord.bountyFee = s.toString()
//                    gratuityAdapter?.checkedPosition = -1
//                    gratuityAdapter?.notifyDataSetChanged()
//                }
//            }
//
//            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//            }
//
//            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//            }
//        })

        binding.layoutCarRemarks.remarkContent.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (s.isNullOrBlank()) {
                    binding.layoutCarRemarks.remarkContent.alpha = 0.2f
                } else {
                    binding.layoutCarRemarks.remarkContent.alpha = 1f
                }
                binding.layoutCarRemarks.remarkCount.text =
                    getString(R.string.remark_count, s.toString().trim().length)

                binding.layoutCarRemarks.remarkContent.setSelection( binding.layoutCarRemarks.remarkContent.length());//将光标移至文字末尾


            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })
    }

    override fun initView(savedInstanceState: Bundle?) {
        progressDialog = AppProgressDialog(this)
        tunnelAdapter = OptionItemAdapter()
        tunnelAdapter?.addOnOptionItemCheckedListener(object : OnOptionItemCheckedListener<Tunnel> {
            override fun onItemChecked(model: Tunnel, position: Int) {
                orderRecord.tunnel = model
                orderRecord.tunnelCode = model.code
            }
        })
        binding.layoutCarTunnel.tunnelRecyclerView.addItemDecoration(
            TripOptionItemDecoration(
                DisplayUtil.dp2px(this, 16f).toInt(),
                DisplayUtil.dp2px(this, 16f).toInt()
            )
        )
        binding.layoutCarTunnel.tunnelRecyclerView.adapter = tunnelAdapter

        gratuityAdapter = OptionItemAdapter()
        gratuityAdapter?.addOnOptionItemCheckedListener(object :
            OnOptionItemCheckedListener<Gratuity> {
            override fun onItemChecked(model: Gratuity, position: Int) {
                //小费
                binding.layoutCarTip.amountOfTip.setText( NumberUtils.forNormalMatNumber(model.fee))
                orderRecord.bountyFee =binding.layoutCarTip.amountOfTip.text.toString()

            }
        })
        binding.layoutCarTip.tipRecyclerView.addItemDecoration(
            TripOptionItemDecoration(
                DisplayUtil.dp2px(this, 16f).toInt(),
                DisplayUtil.dp2px(this, 16f).toInt()
            )
        )
        binding.layoutCarTip.tipRecyclerView.adapter = gratuityAdapter

        carTypeAdapter = OptionItemAdapter()
        carTypeAdapter?.addOnOptionItemCheckedListener(object :
            OnOptionItemCheckedListener<CarCategory> {
            override fun onItemChecked(model: CarCategory, position: Int) {
                orderRecord.carCategory = model
                orderRecord.vehicleTypeCode = model.code
            }
        })
        binding.layoutCarType.carTypeRecyclerView.addItemDecoration(
            TripOptionItemDecoration(
                DisplayUtil.dp2px(
                    this,
                    16f
                ).toInt(), DisplayUtil.dp2px(this, 16f).toInt()
            )
        )
        binding.layoutCarType.carTypeRecyclerView.adapter = carTypeAdapter

        stationAdapter = OptionItemAdapter()
        stationAdapter?.addOnOptionItemCheckedListener(object :
            OnOptionItemCheckedListener<Station> {
            override fun onItemChecked(model: Station, position: Int) {
                orderRecord.stationIndex = model.id
            }
        })
        binding.layoutCarPlatform.platformRecyclerView.addItemDecoration(
            TripOptionItemDecoration(
                DisplayUtil.dp2px(this, 16f).toInt(),
                DisplayUtil.dp2px(this, 16f).toInt()
            )
        )
        binding.layoutCarPlatform.platformRecyclerView.adapter = stationAdapter


        remarkAdapter = RemarkItemAdapter()
        remarkAdapter?.addOnOptionItemCheckedListener(object :
            OnRemarkItemCheckedListener<Remark> {
            override fun onItemChecked(model: Remark, position: Int) {
//                orderRecord.remark += model.contentZhHk
                binding.layoutCarRemarks.remarkContent.setText(binding.layoutCarRemarks.remarkContent.text.toString() + model.name)
            }
        })
        binding.layoutCarRemarks.remarkRecyclerView.addItemDecoration(
            TripOptionItemDecoration(
                DisplayUtil.dp2px(this, 16f).toInt(),
                DisplayUtil.dp2px(this, 16f).toInt()
            )
        )
        binding.layoutCarRemarks.remarkRecyclerView.adapter = remarkAdapter

    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initObserver(savedInstanceState: Bundle?) {
//        progressDialog.show()
//        viewModel.getTravelItem().observe(this, Observer {
//            progressDialog.dismiss()
            binding.content.visibility = View.VISIBLE
//        })
        viewModel.getTunnels().observe(this, Observer { tunnels ->

            initTunnelView(tunnels)
        })

        viewModel.getTips().observe(this, Observer { tips ->
            initGratuityView(tips)
        })

        viewModel.getCarTypes().observe(this, Observer { carTypes ->
            initCarCategoryView(carTypes)
        })
        viewModel.getStations().observe(this, Observer { stations ->
            initStationView(stations)
        })

        viewModel.getRemarks().observe(this, Observer { remarks ->
            initRemarkView(remarks)
        })
    }

    /**
     * 初始化隧道布局，同时高亮已经选择的项
     */
    private fun initTunnelView(tunnels: List<Tunnel>) {
        tunnelAdapter?.submitList(tunnels)
        Handler().postDelayed({
            tunnels.forEachIndexed { index, tunnel ->
                if (tunnel.id == orderRecord.tunnel?.id) {
                    binding.layoutCarTunnel.tunnelRecyclerView.findViewHolderForAdapterPosition(
                        index
                    )?.itemView?.performClick()
                }
            }
        }, 500)
    }

    /**
     * 初始化打赏小费列表，同时高亮已经选择的项
     * @param gratuities 打赏小费列表数据
     */
    private fun initGratuityView(gratuities: List<Gratuity>) {
        val map =
            try {
                gratuities.map {
                    if (it.fee == 0.0) {
                        it.name = getString(R.string.no_reward)
                    } else {
                        it.name = "+HK$ ${NumberUtils.forNormalMatNumber(it.fee.toDouble())} "
                    }
                    it
                }
            }catch (e: Exception) {
                null
            }
        gratuityAdapter?.submitList(map?: gratuities)
        Handler().postDelayed({
            gratuities.forEachIndexed { index, tip ->
                if (tip.fee.toString() == orderRecord.bountyFee?:"0.0") {
                    binding.layoutCarTip.tipRecyclerView.findViewHolderForAdapterPosition(
                        index
                    )?.itemView?.performClick()
                }
            }
        }, 700)
    }

    /**
     * 初始化车种列表，同时高亮已经选择的项
     * @param carTypes 车种列表
     */
    private fun initCarCategoryView(carTypes: List<CarCategory>) {
        carTypeAdapter?.submitList(carTypes)

        Handler().postDelayed({
            carTypes.forEachIndexed { index, carType ->
                if (carType.id == orderRecord.carCategory?.id) {
                    binding.layoutCarType.carTypeRecyclerView.findViewHolderForAdapterPosition(
                        index
                    )?.itemView?.performClick()
                }
            }
        }, 400)
    }

    /**
     * init station list view and checked item that have been checked
     * @param stations station list data.
     */
    private fun initStationView(stations: List<Station>) {
        stationAdapter?.submitList(stations)
        Handler().postDelayed({
            stations.forEachIndexed { index, station ->
                if (station.id == orderRecord.stationIndex) {
                    binding.layoutCarPlatform.platformRecyclerView.findViewHolderForAdapterPosition(
                        index
                    )?.itemView?.performClick()
                }
            }
        }, 1000)//delay to perform click
    }

    private fun initRemarkView(remarks: List<Remark>) {
       // remarkAdapter?.submitList(remarks)

        Handler().postDelayed({
            remarks.forEachIndexed { index, remark ->

                var layout = LayoutInflater.from(this).inflate(R.layout.list_item_on_order_tip_remark_button,null)
                var remarkText =  layout?.findViewById<TextView>(R.id.car_any)
                remarkText?.text = remark.name
                remarkText?.setOnClickListener {
                    //                    if(!layout.isSelected){
//                        layout.isSelected = true
//                        remarkList.add(remark)
//                        orderRecord.remark += remark.contentZhHk


                    var content = binding.layoutCarRemarks.remarkContent.text.toString()
                    if(content.isNullOrBlank()){
                        binding.layoutCarRemarks.remarkContent.setText(remark.name)
                    }else{
                        binding.layoutCarRemarks.remarkContent.setText(content + ", " + remark.name)
                    }
//                    }else{
//                        layout.isSelected = false
//                        remarkList.remove(remark)
//                    }
                }

                binding.layoutCarRemarks.remarkFlexBox.addView(layout)

            }
        }, 1500)
    }

//    private var remarkList = mutableListOf<Remark>()
}
